package cn.com.infcn.monitor.task.jvm;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryManagerMXBean;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import cn.com.infcn.monitor.bean.IFCJVMMemoryManager;
import cn.com.infcn.monitor.task.BaseTask;
import cn.com.infcn.monitor.util.IFCBeanUtils;

/**
 * 内存管理器的管理接口。
 * 
 * 内存管理器管理 Java 虚拟机的一个或多个内存池。
 * 
 * @author jjs
 *
 */
public class JVMMemoryManagerTask implements BaseTask {

	private static final Logger LOGGER = Logger.getLogger(JVMMemoryManagerTask.class);

	@Override
	public List<IFCJVMMemoryManager> execute() throws Exception {
		return jvmMemoryManager();
	}

	public List<IFCJVMMemoryManager> jvmMemoryManager() {

		List<IFCJVMMemoryManager> ifcMemoryManagers = null;
		IFCJVMMemoryManager ifcMemoryManager = null;

		try {
			
			List<MemoryManagerMXBean> memoryManagerMXBeanList = ManagementFactory.getMemoryManagerMXBeans();

			if(memoryManagerMXBeanList != null && memoryManagerMXBeanList.size() > 0){
				ifcMemoryManagers = new ArrayList<IFCJVMMemoryManager>();
				for (MemoryManagerMXBean memoryManagerMXBean : memoryManagerMXBeanList) {
					ifcMemoryManager = new IFCJVMMemoryManager();
					IFCBeanUtils.copyProperties(memoryManagerMXBean, MemoryManagerMXBean.class, ifcMemoryManager);
					
					ifcMemoryManagers.add(ifcMemoryManager);
				}
			}

			return ifcMemoryManagers;
		} catch (Exception e) {
			LOGGER.warn(e.getMessage(), e);
		}

		return null;
	}

	public static void main(String[] args) {

		JVMMemoryManagerTask task = new JVMMemoryManagerTask();
		List<IFCJVMMemoryManager> ifcMemoryManagers = task.jvmMemoryManager();

		for (IFCJVMMemoryManager ifcjvmMemoryManager : ifcMemoryManagers) {
			String[] names = ifcjvmMemoryManager.getMemoryPoolNames();
			if (names != null) {
				for (String str : names) {
					System.out.print(str + "\t");
				}
			}
			System.out.println();
			System.out.println(ifcjvmMemoryManager.getName());
		}
	}

}
